package com.spring.schedule_system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.schedule_system.dao.*;
import com.spring.schedule_system.entity.CommonUser;
import com.spring.schedule_system.entity.User;
import com.spring.schedule_system.service.CommonUserService;
import com.spring.schedule_system.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;

@CrossOrigin
@Controller
@RequestMapping("/user")
@Api(value = "UserController", description = "用户相关api")
public class UserController {
    Boolean flag;
    MyUtil myUtil=new MyUtil();

    @Autowired
    private UserDao userDao;
    @Autowired
    private CommonUserService commonUserService;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private ScheduleDao scheduleDao;
    @Autowired
    private Tb_classDao tb_classDao;
    @Autowired
    private TeacherDao teacherDao;

    /**
     * 微信小程序注册用户接口
     * @param model
     * @param code //用户登录凭证
     * @param rawData  //原始数据
     * @param signature  //署名
     * @param encrypteData  //包括敏感数据在内的完整用户信息的加密数据
     * @param iv  //加密算法的初始向量
     * @return
     */
    @ApiOperation("小程序注册用户")
    @ResponseBody
    @PostMapping("/wx/register")
    public ResponseEntity doRegister(Model model,
                                     @RequestParam(value = "code",required = false) String code,
                                     @RequestParam(value = "rawData",required = false) String rawData,
                                     @RequestParam(value = "signature",required = false) String signature,
                                     @RequestParam(value = "encrypteData",required = false) String encrypteData,
                                     @RequestParam(value = "iv",required = false) String iv){

        ResponseEntity responseData;
        JSONObject rawDataJson = JSON.parseObject( rawData );
        JSONObject SessionKeyOpenId = myUtil.getcode( code );
        String appid = SessionKeyOpenId.getString("openid" );//这里对了吗 //这里的参数是openid
        String sessionKey = SessionKeyOpenId.getString( "session_key" );

        //通过openid来查询此用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", appid);
        User user = userDao.selectOne(queryWrapper);
        System.out.println("当前user为：" + user);
        if(user==null){//但是你下面换了 好像你插入进去你这个user并没有用到，那我换一下试试，但我感觉不是这个问题；我想到的是要么前端返回的参数不对，所以插入的appid没有，要不就是后端代码写不对，插不进去appid；
            responseData = ResponseEntity.ok();
            //入库
            String nickName = rawDataJson.getString( "nickName" );
            String avatar = rawDataJson.getString( "avatarUrl" );

            user = new User();
            user.setUser_name(nickName);
            user.setUser_pwd("1111");
            userDao.insert(user);
            responseData.putDataValue("user_id",user.getUser_id());
            responseData.putDataValue("msg","注册成功");
            responseData.putDataValue("timestamp",myUtil.getTime());
            System.out.println("插入数据库成功");
            return responseData;
        }else {
            //已存在
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","用户已存在");
            responseData.putDataValue("timestamp",myUtil.getTime());
            System.out.println("用户openid已存在,不需要插入");
        }
        return responseData;
    }

    /**
     * 微信小程序登陆接口
     * @param model
     * @param code //用户登录凭证
     * @param rawData  //原始数据
     * @param signature  //署名
     * @param encrypteData  //包括敏感数据在内的完整用户信息的加密数据
     * @param iv  //加密算法的初始向量
     * @return
     * @throws UnsupportedEncodingException
     * @throws JsonProcessingException
     */
    @ApiOperation("微信小程序登录")
    @ResponseBody
    @PostMapping("/wx/login")
    public ResponseEntity doLogin(Model model,
                                  @RequestParam(value = "code",required = false) String code,
                                  @RequestParam(value = "rawData",required = false) String rawData,
                                  @RequestParam(value = "signature",required = false) String signature,
                                  @RequestParam(value = "encrypteData",required = false) String encrypteData,
                                  @RequestParam(value = "iv",required = false) String iv) throws UnsupportedEncodingException, JsonProcessingException {
        ResponseEntity responseEntity;
        JSONObject SessionKeyOpenId = myUtil.getcode( code );
        String appid = SessionKeyOpenId.getString("openid" );
        //JSONObject rawDataJson = JSON.parseObject( rawData );
        String sessionKey = SessionKeyOpenId.getString( "session_key" );
        //通过openid来查询此用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", appid);
        User user = userDao.selectOne(queryWrapper);
        if(user == null){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg", "用户不存在请先授权登录");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }else {
            responseEntity = ResponseEntity.ok();
            //封装成对象返回给客户端
            //给用户jwt加密生成token
            String token = JwtToken.sign(user, 30L * 60L * 1000L);
            responseEntity.putDataValue("User_id", user.getUser_id());
            responseEntity.putDataValue("token", token);
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            responseEntity.putDataValue("msg","登录成功");
        }
        return responseEntity;
    }
    /**
     * 微信获取用户信息接口
     * @param Authorization
     * @param //response
     * @return responseEntity
     * @throws IOException
     */
    @ApiOperation("微信小程序获取用户信息")
    @PostMapping("/wx/getInfo")
    @ResponseBody
    public ResponseEntity getWxInfo(@RequestHeader String Authorization
            /*HttpServletResponse response*/) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (token != null) {
            responseEntity = ResponseEntity.ok();
            User user = JwtToken.unsign(token, User.class);
            //解密token后的identity_id与用户传来的identity_id不一致，大多是因为token过期
            if (user != null) {
                responseEntity.putDataValue("user_id",user.getUser_id());
                responseEntity.putDataValue("user_name",user.getUser_name());
                responseEntity.putDataValue("is_delete",user.getIs_delete());
                responseEntity.putDataValue("update_time",user.getUpdate_time());
                responseEntity.putDataValue("create_time",user.getCreate_time());
                responseEntity.putDataValue("user_role",user.getUser_role());
                responseEntity.putDataValue("head_portrait",user.getUser_headPortrait());
                responseEntity.putDataValue("openid",user.getOpenid());
                responseEntity.putDataValue("scope",user.getScope());
                responseEntity.putDataValue("state",user.getState());
                return responseEntity;
            }
        }
        //token不存在，禁止访问
        responseEntity = ResponseEntity.forbidden();
        return responseEntity;
    }


    /**
     * web端注册用户
     * @param user_name
     * @param user_pwd
     * @param user_role
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     */
    @ApiOperation("web端注册用户")
    @PostMapping("/web/register")
    @ResponseBody
    public ResponseEntity register(@RequestParam(required = true) String user_name,
                                   @RequestParam(required = true) String user_pwd,
                                   @RequestParam(defaultValue = "1") int user_role,
                                   @RequestHeader String Authorization) throws IOException, TokenExpiredException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User user = JwtToken.unsign(token, User.class);
        //用户角色，分微信用户和老师用户，1代表微信用户，2代表老师用户,默认为微信用户
        if (user.getUser_role()!=2){
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        //根据user_jobNumber查询数据库是否有该用户存在，不存在则注册，存在则注册失败
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", user_name);
        User userFromBase = userDao.selectOne(queryWrapper);
        //User userFromBase = userDao.selectById(user_name);
        if (userFromBase == null){
            responseEntity = ResponseEntity.ok();
            User user1 = new User();
            user1.setUser_name(user_name);
            user1.setUser_pwd(user_pwd);
            if (user_role == 1 || user_role == 2) {
                user1.setUser_role(user_role);
            } else {
                responseEntity = ResponseEntity.badRequest();
                responseEntity.putDataValue("msg", "注册失败，权限只能为1或2,1代表微信用户，2代表老师用户");
                return responseEntity;
            }
            int is_delete=0;
            user1.setIs_delete(is_delete);
            userDao.insert(user1);
            responseEntity.putDataValue("user_id",user1.getUser_id());
            responseEntity.putDataValue("msg","注册成功");
        }else {
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","注册失败");
        }

        return responseEntity;
    }

    /**
     * web登录接口
     * @param user_name
     * @param user_pwd
     *
     */
    @ApiOperation("web端登录")
    @PostMapping("/web/login")
    @ResponseBody
    public ResponseEntity login(@RequestParam(required = true) String user_name, @RequestParam(required = true) String user_pwd) throws IOException {
          ResponseEntity responseEntity = ResponseEntity.ok();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", user_name);
        User userFromBase = userDao.selectOne(queryWrapper);//这里错 登录的时候先查查输入的用户工号这个人的信息，逻辑对的吧
       // User userFromBase = userDao.selectById(user_name);
        if(userFromBase==null){
            responseEntity =  ResponseEntity.customerError();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        }
        if(userFromBase.getUser_name().equals(user_name) &&
                userFromBase.getUser_pwd().equals(user_pwd)) {
            //给用户jwt加密生成token
            String token = JwtToken.sign(userFromBase, 60L * 1000L * 30L);//sign()方法是static修饰的，所以直接用类名调用，不需要创建对象
            //封装成对象返回给客户端
            responseEntity.putDataValue("id",userFromBase.getUser_id());
            responseEntity.putDataValue("user_name", userFromBase.getUser_name());//调用ResponseEntity类的putDataValue方法将userID和token放进map中然后返回
            responseEntity.putDataValue("token", token);
            responseEntity.putDataValue("user_role",userFromBase.getUser_role());
            /* BS架构中,客户端与服务器一连接在服务端就会自动创建一来个session对象.session.setAttribute("username",username);
这句话的意思就是自说,当客户端执行了某个操作后(刚一登陆,或其他操作)服务百端就会在session对象中存储一个名称为username的参数这个相当于hashMap,
"username" 相当于key username就是key对应的值(但注意这个值度必须是一个对象知).这样以后你可以通过session.getAttribute("username")的方法获得这个对象.
比如说,当用户道已登录系统后你就在session中存储了一个用户信息对象,此后你可以随时从session中将这个对象取出来进行一些操作,比如进行身份验证等等.
             */
        }
        else{
            responseEntity =  ResponseEntity.customerError();
            responseEntity.putDataValue("msg","账号密码错误");
        }
        return responseEntity;
    }

    /**
     *
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation("导入教学计划")
    @PostMapping("/web/upload")
    @ResponseBody
    public ResponseEntity upload(@RequestParam(required = true) MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), CommonUser.class, new CommonUserListener(commonUserService))
                .sheet()
                .doRead();
        courseDao.insertCourse();
        scheduleDao.insertSchedule();
        tb_classDao.insertClass();
        teacherDao.insertTeacher();
        ResponseEntity responseEntity = ResponseEntity.ok();
        return responseEntity;

    }
    /**
     * 获取当前登录用户信息
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation("web端获取当前登录用户信息")
    @PostMapping("/web/getinfo")
    @ResponseBody
    public ResponseEntity preHandle(@RequestHeader String Authorization,
                                    HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        String token = Authorization;
        ResponseEntity responseData;
        //token不存在
        if (token != null) {
            responseData = ResponseEntity.ok();
            User user = JwtToken.unsign(token, User.class);
            //解密token后的userId与用户传来的userId不一致，大多是因为token过期
            if (user != null) {
                responseData.putDataValue("user_id",user.getUser_id());
                responseData.putDataValue("user_name",user.getUser_name());
                responseData.putDataValue("user_role",user.getUser_role());
                responseData.putDataValue("user_phone",user.getUser_phone());
                responseData.putDataValue("address",user.getAddress());
                responseData.putDataValue("remark",user.getRemark());
                responseData.putDataValue("user_headPortrait",user.getUser_headPortrait());
                responseData.putDataValue("create_time",user.getCreate_time());
                responseData.putDataValue("update_time",user.getUpdate_time());
                responseData.putDataValue("is_delete",user.getIs_delete());
                return responseData;
            }
        }
        responseData = ResponseEntity.forbidden();
        response.setContentType("application/json; charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(responseData);
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
        return responseData;
    }

    /**修改自己信息
     *
     * @param user_name
     * @param user_pwd
     * @param user_phone
     * @param address
     * @param remark
     * @param pictureFile
     * @param request
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @ApiOperation("修改自己信息")
    @RequestMapping(value = "/web/update_info",method  = RequestMethod.POST, consumes = "multipart/form-data")
    @ResponseBody
    public ResponseEntity updateUserInfoByMyself(@RequestParam(required = false) String user_name,
                                                 @RequestParam(required = false) String user_pwd,
                                                 @RequestParam(required = false) String user_phone,
                                                 @RequestParam(required = false) String address,
                                                 @RequestParam(required = false) String remark,
                                                 @RequestParam(required = false) MultipartFile pictureFile,
                                                 HttpServletRequest request,
                                                 @RequestHeader String Authorization,
                                                 HttpServletResponse response) throws IOException, ParseException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData=null;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user == null){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","没有该用户");
        }else {
            //图片资源访问路径
            String fileLocation = "/static/restaurantRes/";
            //获取提交文件名称
            String filename = pictureFile.getOriginalFilename();
            String newfilename = System.currentTimeMillis() + UUID.randomUUID().toString().replace(".", "").substring(0, 6) + "." + filename.substring(filename.lastIndexOf(".") + 1);

            //定义上传文件存放的路径
            String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
            System.out.println(path);
            //返回保存的url，根据url可以进行文件查看或者下载
            String filePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() //端口 https443端口无需添加
                    + fileLocation + newfilename;

            String head_portrait = filePath;//根路径+文件名
            File file = new File("/www/javaweb/schedule_system/picture/" + newfilename);
            pictureFile.transferTo(file);
            user.setUser_headPortrait(head_portrait);
//            if (myUtil.isNumLegal(user_phone)) {
//                user.setUser_phone(user_phone);
//            } else {
//                responseData.putDataValue("msg", "手机号码长度不是11位不合法");
//            }
            user.setUser_phone(user_phone);
            user.setAddress(address);
            user.setRemark(remark);
            user.setUser_name(user_name);
            user.setUser_pwd(user_pwd);
            //修改信息
            userDao.updateById(user);
            responseData = ResponseEntity.ok();
            User users=userDao.selectById(user.getUser_id());
            responseData.putDataValue("users",users);
            responseData.putDataValue("msg","修改数据成功");
            System.out.println("修改数据成功");
        }
        return responseData;
    }

    /**
     * 根据user_name查询用户信息
     * @param user_name
     * @param Authorization
     * @return
     * @throws Exception
     */
    @ApiOperation("根据user_name查询用户信息")
    @GetMapping("/web/selectUserByUserName")
    @ResponseBody
    public ResponseEntity selectUserByIdentityId(@RequestParam(value = "user_name",required = true) String user_name, @RequestHeader String Authorization)
            throws Exception {
        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        responseData = ResponseEntity.ok();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", user_name);
        User userFromBase = userDao.selectOne(wrapper);
        responseData.putDataValue("user", userFromBase);
        return responseData;

    }

    /**
     * 用户列表接口
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("用户列表")
    @PostMapping("/web/users_list")
    @ResponseBody
    public ResponseEntity selectUsers(@RequestHeader String Authorization,
                                      HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user.getUser_role()!=2){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","权限错误");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        List<User> list = userDao.selectList(wrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("user",list);
        responseData.putDataValue("msg","成功");
        return responseData;
    }
    /**
     * 删除用户
     * @param user_id
     * @return
     * @throws IOException
     */
    @ApiOperation("删除用户")
    @GetMapping("/web/delete")
    @ResponseBody
    public ResponseEntity deleteUser(@RequestParam(required = true) Integer user_id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user.getUser_role()!=2){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","权限错误");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        User user1 = userDao.selectById(user_id);
        int is_delete = 1;
        user1.setIs_delete(is_delete);
        userDao.updateById(user1);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("msg", "删除数据成功");
        return responseData;
    }
    /**
     * 统计用户数量
     */
    @ApiOperation("统计用户数量")
    @GetMapping("/web/count")
    @ResponseBody
    public ResponseEntity count() throws IOException {
        ResponseEntity responseData;
        int is_delete = 0;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", is_delete);
        int  count =userDao.selectCount(queryWrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("count", count);
        return responseData;
    }

    /**
     * 批量删除用户
     * @param arr
     * @param Authorization
     * @return
     */
    @ApiOperation("批量删除用户")
    @GetMapping("/web/deleteUserList")
    @ResponseBody
    public ResponseEntity deleteUserList(@RequestParam(required = true) int[] arr,
                                         @RequestHeader String Authorization ) throws  IOException{
        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user.getUser_role()!=2){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","权限错误");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        for (int user_id : arr) {
            User user1 = userDao.selectById(user_id);
            int is_delete = 1;
            user1.setIs_delete(is_delete);
            userDao.updateById(user1);
        }
        responseData = ResponseEntity.ok();
        responseData.putDataValue("msg", "批量删除数据成功");
        return responseData;


    }
}
